<template>
  <div flex="~ col">
    <div>
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="用户名">
          <el-input v-model="queryForm.keyword" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="mb-4 flex justify-end">
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>
    <!-- <el-scrollbar height="400px"> -->
    <el-table :data="tableData" border style="width: 100%" height="400">
      <el-table-column prop="username" label="用户名" fixed />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="email" label="邮箱" width="200" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="userType" label="用户类型">
        <template #default="{ row }">
          <el-tag
            :type="
              row.userType === 'ADMIN'
                ? 'danger'
                : row.userType === 'USER'
                  ? 'primary'
                  : row.userType === 'FAMILY'
                    ? 'warning'
                    : row.userType === 'MEDICAL'
                      ? 'success'
                      : 'info'
            "
          >
            {{
              row.userType === 'ADMIN'
                ? '管理员'
                : row.userType === 'USER'
                  ? '普通用户'
                  : row.userType === 'FAMILY'
                    ? '家属'
                    : row.userType === 'MEDICAL'
                      ? '医护'
                      : '暂无角色'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button link type="success" @click="handleAssignRole(row)">绑定</el-button>
          <el-button link type="danger" @click="handleDeleteUserRole(row)">解绑</el-button>
          <el-button link type="warning" @click="handleRobotManage(row)">绑定机器</el-button>
          <el-button v-if="row.userType === 'USER'" link type="info" @click="handleViewDetail(row)">
            关联联系人
          </el-button>
          <el-button
            v-if="row.userType === 'USER'"
            link
            type="info"
            @click="handleFamilyRelation(row)"
            >关联家属</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- </el-scrollbar> -->

    <div class="flex justify-end mt-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-drawer v-model="robotDrawerVisible" title="机器人管理" size="60%" destroy-on-close>
      <div class="p-4">
        <div class="mb-6">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">绑定新机器人</h3>
          </div>
          <el-form
            :model="robotBindForm"
            :rules="robotBindRules"
            ref="robotBindFormRef"
            label-width="120px"
          >
            <el-form-item label="机器人地址" prop="robotMac">
              <el-input
                v-model="robotBindForm.robotMac"
                placeholder="请输入机器人MAC地址，例如：12:34:56:78:90:AB"
                style="width: 70%"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleBindRobot" :loading="bindLoading">
                确定绑定
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <div>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">已绑定机器人列表</h3>
          </div>
          <el-table
            :data="robotList"
            border
            v-loading="robotLoading"
            style="width: 100%"
            height="400px"
          >
            <el-table-column prop="mac" label="机器人MAC" width="180" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '在线' : '离线' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="navStatus" label="导航状态" width="120">
              <template #default="{ row }">
                <el-tag
                  :type="
                    row.navStatus === 2
                      ? 'info'
                      : row.navStatus === 3
                        ? 'warning'
                        : row.navStatus === 4
                          ? 'primary'
                          : 'danger'
                  "
                >
                  {{
                    row.navStatus === 2
                      ? '导航待机'
                      : row.navStatus === 3
                        ? '导航中'
                        : row.navStatus === 4
                          ? '遥控模式'
                          : '导航故障'
                  }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="speed" label="速度(m/s)" width="100" />
            <el-table-column prop="wheelStatus" label="运动系统" width="120">
              <template #default="{ row }">
                <el-tag :type="row.wheelStatus === 1 ? 'success' : 'danger'">
                  {{ row.wheelStatus === 1 ? '正常' : '异常' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button link type="danger" @click="handleUnbindRobot(row)"> 解绑 </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-drawer>
    <!-- 家属关联抽屉 -->
    <el-drawer v-model="familyDrawerVisible" title="家属关联管理" size="50%" destroy-on-close>
      <div class="p-4">
        <!-- <div class="mb-6">
          <h3 class="text-lg font-semibold mb-4">用户信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="昵称">{{
              currentFamilyUser.nickname
            }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{
              currentFamilyUser.username
            }}</el-descriptions-item>
          </el-descriptions>
        </div> -->

        <div>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">添加家属关联</h3>
          </div>

          <el-form :model="familyRelationForm" label-width="100px">
            <el-form-item label="选择家属">
              <el-select
                v-model="familyRelationForm.familyId"
                placeholder="请选择家属"
                clearable
                style="width: 100%"
                v-loading="familyListLoading"
                filterable
              >
                <el-option
                  v-for="family in userFamilyList"
                  :key="family.id"
                  :label="`${family.familyId}(${family.username})`"
                  :value="family.familyId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="关系类型">
              <el-select
                v-model="familyRelationForm.relationType"
                placeholder="请选择关系类型"
                style="width: 100%"
              >
                <el-option label="父亲" value="father" />
                <el-option label="母亲" value="mother" />
                <el-option label="配偶" value="spouse" />
                <el-option label="子女" value="child" />
                <el-option label="兄弟姐妹" value="sibling" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handleCreateFamilyRelation"
                :disabled="!familyRelationForm.familyId || !familyRelationForm.relationType"
              >
                确定关联
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <div class="mb-6">
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">已关联家属</h3>
          </div>
          <el-scrollbar height="400px">
            <el-table :data="userFamilyList" border v-loading="familyLoading">
              <el-table-column prop="familyId" label="家属id" />
              <!-- <el-table-column prop="familyUsername" label="家属用户名" /> -->
              <el-table-column prop="relationType" label="关系类型" />
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button link type="danger" @click="handleDeleteFamilyRelation(row)"
                    >解绑</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
      </div>
    </el-drawer>
    <!-- 用户详情抽屉 -->
    <el-drawer v-model="detailDrawerVisible" title="用户详情" size="60%" destroy-on-close>
      <div class="p-4">
        <div class="mb-6">
          <h3 class="text-lg font-semibold mb-4">基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="昵称">{{
              currentUserDetail.nickname
            }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{
              currentUserDetail.username
            }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ currentUserDetail.email }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{
              currentUserDetail.phone
            }}</el-descriptions-item>
            <el-descriptions-item label="用户类型">
              <el-tag
                :type="
                  currentUserDetail.userType === 'ADMIN'
                    ? 'danger'
                    : currentUserDetail.userType === 'USER'
                      ? 'primary'
                      : currentUserDetail.userType === 'FAMILY'
                        ? 'warning'
                        : currentUserDetail.userType === 'MEDICAL'
                          ? 'success'
                          : 'info'
                "
              >
                {{
                  currentUserDetail.userType === 'ADMIN'
                    ? '管理员'
                    : currentUserDetail.userType === 'USER'
                      ? '普通用户'
                      : currentUserDetail.userType === 'FAMILY'
                        ? '家属'
                        : currentUserDetail.userType === 'MEDICAL'
                          ? '医护'
                          : '暂无角色'
                }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentUserDetail.status === 1 ? 'success' : 'danger'">
                {{ currentUserDetail.status === 1 ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <div>
          <div class="flex justify-between items-center mb-4">
            <h3 class="text-lg font-semibold">联系人信息</h3>
            <el-button type="primary" @click="handleAddContact">新增联系人</el-button>
          </div>
          <el-scrollbar height="400px">
            <el-table :data="contactList" border v-loading="contactLoading">
              <el-table-column prop="username" label="联系人姓名" />
              <el-table-column prop="email" label="联系人邮件" />
              <el-table-column prop="number" label="联系人电话" />
              <el-table-column label="操作" width="150">
                <template #default="{ row }">
                  <el-button link type="primary" @click="handleEditContact(row)">编辑</el-button>
                  <el-button link type="danger" @click="handleDeleteContact(row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-scrollbar>
        </div>
      </div>
    </el-drawer>

    <!-- 联系人信息弹窗 -->
    <el-dialog
      v-model="contactDialogVisible"
      :title="contactDialogType === 'add' ? '新增联系人' : '编辑联系人'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="contactFormRef"
        :model="contactForm"
        :rules="contactFormRules"
        label-width="100px"
      >
        <el-form-item label="联系人姓名" prop="username">
          <el-input v-model="contactForm.username" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系人邮件" prop="email">
          <el-input v-model="contactForm.email" placeholder="请输入联系人邮件" />
        </el-form-item>
        <el-form-item label="联系人电话" prop="number">
          <el-input v-model="contactForm.number" placeholder="请输入联系人电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="contactDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitContact">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增用户' : '编辑用户'"
      width="500px"
      destroy-on-close
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <!-- <el-form-item label="编码" prop="id">
          <el-input v-model="form.id" placeholder="请输入用户id" />
        </el-form-item> -->
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <!-- <el-form-item label="用户类型" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择用户类型">
            <el-option label="管理员" :value="'ADMIN'" />
            <el-option label="普通用户" :value="'USER'" />
            <el-option label="家属" :value="'FAMILY'" />
            <el-option label="医护" :value="'MEDICAL'" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="roleDialogVisible" title="分配角色" width="500px" destroy-on-close>
      <el-form :model="roleform" ref="roleFormRef" label-width="80px" style="margin-top: 20px">
        <el-form-item
          label="角色"
          prop="roleId"
          :rules="[{ required: true, message: '请选择角色', trigger: 'change' }]"
        >
          <el-select
            v-model="roleform.roleId"
            placeholder="请选择角色"
            clearable
            style="width: 100%"
            v-loading="drawerLoading"
          >
            <el-option
              v-for="role in roleData"
              :key="role.id"
              :label="role.roleName"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="flex justify-end">
          <el-button @click="handleCancelAssignRole">取消</el-button>
          <el-button type="primary" @click="handleConfirmAssignRole"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
// import TreeStore from 'element-plus/es/components/tree/src/model/tree-store'
import { computed, nextTick, onMounted, ref, watch } from 'vue'
import { fetchList as fetchRoleList } from '../../../api/role.js'
import {
  assignUserRole,
  updateUserRole,
  createUser,
  deleteUser,
  fetchList,
  // getRolesByUser,
  updateUser,
  deleteUserRole,
  addUserByContact,
  getUserByContact,
  updateUserByContact,
  deleteUserByContact,
  getUserContactList
} from '../../../api/user.js'
import type { CreateUserParams } from '../../../types/user'
import { useUserStore } from '../../../store/user'
import {
  // ... existing imports ...
  addUserByFamily,
  getUserFamilyList,
  deleteUserFamily
} from '../../../api/user.js'
import { getRobotList, bindRobot, unbindRobot } from '../../../api/robot.js'
const userStore = useUserStore()

/**
 * 联系人数据接口
 */
interface ContactItem {
  id?: number | null
  username: string
  email: string
  number: string
  userId?: number | null
}

// 用户详情相关
const detailDrawerVisible = ref(false)
const currentUserDetail = ref<UserRow>({} as UserRow)
const contactList = ref<ContactItem[]>([])
const contactLoading = ref(false)

// 联系人弹窗相关
const contactDialogVisible = ref(false)
const contactDialogType = ref<'add' | 'edit'>('add')
const contactFormRef = ref<FormInstance>()

const defaultContactForm: ContactItem = {
  id: null,
  username: '',
  email: '',
  number: '',
  userId: null
}

const contactForm = ref<ContactItem>({ ...defaultContactForm })

const contactFormRules = {
  username: [{ required: true, message: '请输入联系人姓名' }],
  email: [{ required: true, message: '请输入联系人邮件', type: 'email' }],
  number: [{ required: true, message: '请输入联系人电话', pattern: /^1[3-9]\d{9}$/ }]
}

// 家属关联相关
const familyDrawerVisible = ref(false)
const currentFamilyUser = ref<UserRow>({} as UserRow)
const userFamilyList = ref<any[]>([])
const allFamilyList = ref<any[]>([])
const familyLoading = ref(false)
const familyListLoading = ref(false)

const familyRelationForm = ref({
  userId: null as number | null,
  familyId: null as number | null,
  relationType: ''
})

// 计算可选择的家属列表（排除已关联的）
const availableFamilyList = computed(() => {
  const relatedFamilyIds = userFamilyList.value.map((item) => item.id)
  return allFamilyList.value.filter(
    (family) => !relatedFamilyIds.includes(family.id) && family.id !== currentFamilyUser.value.id
  )
})

/**
 * 用户行数据接口
 */
interface UserRow {
  id: number
  username: string
  nickname: string
  email: string
  phone: string
  userType: string
  roleCode: ''
  status: number
  password?: string
}

/**
 * 角色数据接口
 */
interface RoleItem {
  id: number | null
  roleName: string
  roleCode: string
}

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

const hasRole = ref<'addRole' | 'updateRole'>('addRole')

const roleFormRef = ref<FormInstance>()

const queryForm = ref({
  keyword: '',
  page: 1,
  limit: 10
})

const defaultForm: UserRow = {
  id: null,
  username: '',
  nickname: '',
  roleCode: '',
  // companyId: '',
  email: '',
  phone: '',
  userType: '',
  status: 1,
  password: ''
  // note: ''
}

const form = ref<UserRow>({ ...defaultForm })

const defaultRoleForm = {
  roleId: null
}
const roleform = ref({ ...defaultRoleForm })

const formRules = {
  // id: [{ required: true, message: '请输入id' }],
  username: [{ required: true, message: '请输入账号' }],
  password: [{ required: true, message: '请输入密码' }],
  companyId: [{ required: true, message: '请绑定车站' }],
  email: [{ required: true, message: '请输入邮箱', type: 'email' }],
  phone: [{ required: true, message: '请输入手机号', pattern: /^1[3-9]\d{9}$/ }],
  userType: [{ required: true, message: '请选择用户类型' }],
  status: [{ required: true, message: '请选择状态' }]
}

const roleDialogVisible = ref(false)
const drawerLoading = ref(false)
const roleData = ref([])
// const treeRef = ref<TreeStore>()
const userId = ref()
// const roleId = ref()
/**
 * 获取用户列表数据
 */
const getList = async () => {
  const params = {
    page: currentPage.value,
    limit: pageSize.value,
    keyword: queryForm.value.keyword
  }

  try {
    const res = await fetchList(params)
    tableData.value = res.data.list
    total.value = res.data.total
  } catch {
    ElMessage.error('获取用户列表失败')
  }
}

/**
 * 处理每页显示数量变化
 */
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

/**
 * 处理页码变化
 */
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

/**
 * 处理查询操作
 */
const handleQuery = () => {
  currentPage.value = 1
  getList()
}

/**
 * 重置查询表单
 */
const resetQuery = () => {
  queryForm.value = {
    keyword: '',
    page: 1,
    limit: 10
  }
  currentPage.value = 1
  getList()
}

/**
 * 处理新增用户
 */
const handleAdd = () => {
  form.value = { ...defaultForm }
  dialogType.value = 'add'
  dialogVisible.value = true
}

/**
 * 处理编辑用户
 */
const handleEdit = (row: UserRow) => {
  form.value = { ...row }
  dialogType.value = 'edit'
  dialogVisible.value = true
}

/**
 * 处理删除用户
 */
const handleDelete = (row: UserRow) => {
  if (!row.id) return

  ElMessageBox.confirm('确认删除该用户吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteUser(row.id)
        ElMessage.success('删除成功')
        getList()
      } catch {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (dialogType.value === 'add') {
        await createUser(form.value as CreateUserParams)
        ElMessage.success('添加成功')
      } else {
        await updateUser(form.value)
        ElMessage.success('更新成功')
      }

      dialogVisible.value = false
      getList()
    } catch {
      ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
    }
  })
}

/**
 * 处理分配角色
 */

async function handleAssignRole(row: UserRow) {
  hasRole.value = 'addRole'
  roleform.value = { ...defaultRoleForm }
  userId.value = row.id
  roleDialogVisible.value = true
  drawerLoading.value = true
  try {
    let res = await fetchRoleList({ page: 1, limit: 999999 })
    roleData.value = res.data.list
    // 获取当前用户的角色代码
    const userRoleCode = row?.userType

    const matchedRole = roleData.value.find((item: RoleItem) => item.roleCode === userRoleCode)

    if (matchedRole) {
      console.log(hasRole.value)

      await nextTick()
      roleform.value.roleId = matchedRole.id
      hasRole.value = 'updateRole'
    }
  } catch {
    ElMessage.error('获取角色数据失败')
  } finally {
    drawerLoading.value = false
  }
}

async function handleConfirmAssignRole() {
  if (!roleFormRef.value) return

  try {
    const data = {
      userId: userId.value,
      roleId: roleform.value.roleId
    }
    if (!data.roleId) {
      ElMessage({ type: 'error', message: '请选择角色' })
      return
    }
    if (hasRole.value === 'addRole') {
      await assignUserRole(data)
      ElMessage.success('添加成功')
    } else {
      await updateUserRole(data)
      ElMessage.success('更新成功')
    }

    roleDialogVisible.value = false
    getList()
  } catch {
    ElMessage.error('绑定角色失败')
  } finally {
    drawerLoading.value = false
  }
}

/**
 * 处理删除用户角色关联
 */
const handleDeleteUserRole = (row: UserRow) => {
  if (!row.id) return

  ElMessageBox.confirm('确认解绑该用户吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        if (row.userType) {
          await deleteUserRole(row.id)
          ElMessage.success('解绑成功')
          getList()
        } else {
          ElMessage.warning('当前用户未绑定角色')
        }
      } catch {
        ElMessage.error('解绑失败')
      }
    })
    .catch(() => {})
}

/**
 * 取消分配角色
 */
function handleCancelAssignRole() {
  roleDialogVisible.value = false
}

/**
 * 处理查看用户详情
 */
const handleViewDetail = async (row: UserRow) => {
  // 只允许查看普通用户的详情
  if (row.userType !== 'USER') {
    ElMessage.warning('只能查看普通用户的详情')
    return
  }

  currentUserDetail.value = { ...row }
  detailDrawerVisible.value = true
  await getContactList(row.id)
}

/**
 * 获取联系人列表
 */
const getContactList = async (userId: number | null) => {
  if (!userId) return

  contactLoading.value = true
  try {
    const res = await getUserContactList(userId)
    contactList.value = res.data || []
  } catch {
    ElMessage.error('获取联系人列表失败')
  } finally {
    contactLoading.value = false
  }
}

/**
 * 处理新增联系人
 */
const handleAddContact = () => {
  contactForm.value = { ...defaultContactForm, userId: currentUserDetail.value.id }
  contactDialogType.value = 'add'
  contactDialogVisible.value = true
}

/**
 * 处理编辑联系人
 */
const handleEditContact = (row: ContactItem) => {
  contactForm.value = { ...row }
  contactDialogType.value = 'edit'
  contactDialogVisible.value = true
}

/**
 * 处理删除联系人
 */
const handleDeleteContact = (row: ContactItem) => {
  if (!row.id) return

  ElMessageBox.confirm('确认删除该联系人吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        console.log(row)

        await deleteUserByContact(row.id)
        ElMessage.success('删除成功')
        await getContactList(currentUserDetail.value.id)
      } catch {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

/**
 * 提交联系人表单
 */
const handleSubmitContact = async () => {
  if (!contactFormRef.value) return

  await contactFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      if (contactDialogType.value === 'add') {
        await addUserByContact(contactForm.value)
        ElMessage.success('添加成功')
      } else {
        await updateUserByContact(contactForm.value)
        ElMessage.success('更新成功')
      }

      contactDialogVisible.value = false
      await getContactList(currentUserDetail.value.id)
    } catch {
      ElMessage.error(contactDialogType.value === 'add' ? '添加失败' : '更新失败')
    }
  })
}

/**
 * 处理家属关联
 */
const handleFamilyRelation = async (row: UserRow) => {
  currentFamilyUser.value = { ...row }
  familyRelationForm.value.userId = row.id
  familyRelationForm.value.familyId = null
  familyRelationForm.value.relationType = ''
  familyDrawerVisible.value = true

  // 获取已关联的家属列表
  await getUserFamilyRelations(row.id)
  // 获取所有家属用户列表
  await getAllFamilyUsers(row.id)
}

/**
 * 获取用户已关联的家属列表
 */
const getUserFamilyRelations = async (userId: number) => {
  if (!userId) return

  familyLoading.value = true
  try {
    const res = await getUserFamilyList({ userId })
    userFamilyList.value = res.data?.list || []
  } catch {
    ElMessage.error('获取家属关联列表失败')
  } finally {
    familyLoading.value = false
  }
}

/**
 * 获取所有家属用户列表
 */
const getAllFamilyUsers = async (userId: number) => {
  familyListLoading.value = true
  try {
    const res = await fetchList({ userId })

    allFamilyList.value = res.data?.list || []
  } catch {
    ElMessage.error('获取家属用户列表失败')
  } finally {
    familyListLoading.value = false
  }
}

/**
 * 创建家属关联
 */
const handleCreateFamilyRelation = async () => {
  if (!familyRelationForm.value.familyId || !familyRelationForm.value.relationType) {
    ElMessage.warning('请选择家属和关系类型')
    return
  }

  try {
    const data = {
      userId: familyRelationForm.value.userId,
      familyId: familyRelationForm.value.familyId,
      relationType: familyRelationForm.value.relationType
    }

    await addUserByFamily(data)
    ElMessage.success('关联成功')

    // 重置表单
    familyRelationForm.value.familyId = null
    familyRelationForm.value.relationType = ''

    // 刷新已关联列表
    await getUserFamilyRelations(currentFamilyUser.value.id)
  } catch {
    ElMessage.error('关联失败')
  }
}

/**
 * 删除家属关联
 */
const handleDeleteFamilyRelation = (row: any) => {
  if (!row.id) return

  ElMessageBox.confirm('确认解除与该家属的关联吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteUserFamily(row.id, currentFamilyUser.value.id)
        ElMessage.success('解绑成功')
        await getUserFamilyRelations(currentFamilyUser.value.id)
      } catch {
        ElMessage.error('解绑失败')
      }
    })
    .catch(() => {})
}

// 机器人管理相关
const robotDrawerVisible = ref(false)
const currentRobotUser = ref<UserRow>({} as UserRow)
const robotList = ref<RobotItem[]>([])
const robotLoading = ref(false)
const bindLoading = ref(false)
const robotBindFormRef = ref<FormInstance>()

/**
 * 机器人数据接口
 */
interface RobotItem {
  id?: number
  mac: string
  navStatus: number
  speed: number
  status: number
  updateTime: string
  userId: number
  wheelStatus: number
}

const defaultRobotBindForm = {
  robotMac: '',
  userId: null as number | null
}

const robotBindForm = ref({ ...defaultRobotBindForm })

const robotBindRules = {
  robotMac: [
    { required: true, message: '请输入机器人MAC地址' },
    {
      pattern: /^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$/,
      message: 'MAC地址格式不正确，例如：12:34:56:78:90:AB'
    }
  ]
}
/**
 * 处理机器人管理
 */
const handleRobotManage = async (row: UserRow) => {
  currentRobotUser.value = { ...row }
  robotBindForm.value.userId = row.id
  robotBindForm.value.robotMac = ''
  robotDrawerVisible.value = true

  // 获取用户的机器人列表
  await getRobotListByUser(row.id)
}

/**
 * 获取用户的机器人列表
 */
const getRobotListByUser = async (userId: number | null) => {
  if (!userId) return

  robotLoading.value = true
  try {
    const res = await getRobotList(userId)
    robotList.value = res.data?.list || [
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 },
      { mac: '4541212', navStatus: 2, status: 0, wheelStatus: 1, speed: 5 }
    ]
  } catch {
    ElMessage.error('获取机器人列表失败')
  } finally {
    robotLoading.value = false
  }
}
/**
 * 处理绑定机器人
 */
const handleBindRobot = async () => {
  if (!robotBindFormRef.value) return

  await robotBindFormRef.value.validate(async (valid) => {
    if (!valid) return

    bindLoading.value = true
    try {
      await bindRobot({
        robotMac: robotBindForm.value.robotMac,
        userId: robotBindForm.value.userId!
      })
      ElMessage.success('绑定成功')

      // 重置表单
      robotBindForm.value.robotMac = ''

      // 刷新机器人列表
      await getRobotListByUser(currentRobotUser.value.id)
    } catch {
      ElMessage.error('绑定失败')
    } finally {
      bindLoading.value = false
    }
  })
}
/**
 * 处理解绑机器人
 */
const handleUnbindRobot = (row: RobotItem) => {
  console.log(row)

  if (!row.id) return

  ElMessageBox.confirm('确认删除该机器人绑定吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        console.log(row)

        await unbindRobot(row.id!)
        ElMessage.success('删除成功')
        await getRobotListByUser(currentRobotUser.value.id)
      } catch {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

watch(
  () => userStore.token,
  (newToken) => {
    if (newToken) {
      getList()
    }
  }
)

onMounted(() => {
  if (userStore.token) {
    getList()
  }
})

// 暴露给父组件的方法
defineExpose({
  getList
})
/**
 * 处理角色选择
 */
// const handleRoleSelect = (row: RoleItem | null) => {
//   if (row) {
//     currentRow.value = row
//     console.log(row)

//     roleId.value = row.id
//   }
// }
</script>

<style lang="scss" scoped>
:deep(.el-form-item__content) {
  @apply w-64;
}

:deep(.el-drawer__body) {
  @apply p-6;
}
</style>
